# -*- coding: UTF-8 -*-

import os, sys, cmd, glob, time, datetime, codecs
from optparse import OptionParser

__VERSION__ = '0.1.0'
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage, version="pySCC " + __VERSION__)

def initial_command_option():
    
    parser.add_option("-p", "--path", dest="path",
                      help="write report to FILE", metavar="FILE")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=False,
                      help="don’t print status messages to stdout")
    parser.add_option("-o", "--output", dest="output_file_type",
                      help="write report to FILE", metavar="FILE")
    parser.add_option("-t", "--type", dest="count_file_type", type="string", default='py',
                      help="write report to FILE")
    parser.add_option("-g", "--gui", action="store_true",
                      dest="gui", default=False, 
                      help="whether run on GUI")

def counter_python(filename):
    line_comments = 0
    line_source = 0
    line_space = 0
    line_total = 0

    for line in open(filename, "r"):
        line_total += 1
        line = line.strip()
        if line == '': 
            line_space += 1
        if line.startswith('#'):
            line_comments += 1
        else:
            line_source += 1
    #filename = os.path.basename(filename)
    print '%s\t%d\t%d\t%d\t%d' % (filename, line_total, line_source, line_comments, line_space)
    
    file_result = [line_total, line_source, line_comments, line_space]
    
    return file_result

def counter_cs(filename):
    line_comments = 0
    line_source = 0
    line_space = 0
    line_total = 0
    
    flag_mutil_comment = False
    
    for line in open(filename, "r"):
        line_total += 1
        line = line.strip()
        
        #Blank line
        if line == '': 
            line_space += 1
            continue
        
        if flag_mutil_comment:
            line_comments += 1
            
            if line.endswith('*/'):
                flag_mutil_comment = False
            continue
        
        if line.startswith('/*'):
            line_comments += 1
            flag_mutil_comment = True
            continue
        
        # single line comments line
        if line.startswith('//') or line.startswith('#region') or line.startswith('#endregion'):
            line_comments += 1
            continue
        
        # source line
        line_source += 1
    
    #print '%s\t%d\t%d\t%d\t%d' % (filename, line_total, line_source, line_comments, line_space)
    
    file_result = [filename, line_total, line_source, line_comments, line_space]
    
    return file_result
    
def counter_java(filename):
    return counter_cs(filename)
    
def report_console(filename):
    print 'console'

def report_xml(filename):
    print 'Xml'
    
def report_csv(filename, result):
    file = open('report.csv', 'w')
    file.write('\"File name\",\"Total line\",\"Code line\",\"Comment line\",\"Blank line\"\r')
    for t_result in result:
        file.write('\"%s\",\"%d\",\"%d\",\"%d\",\"%d\"\r' % \
                   (t_result[0], t_result[1], t_result[2], t_result[3],t_result[4]))
    file.close()
    
SUPPORT_FILE_TYPE = {
                     'cs':counter_cs,
                     'java':counter_java,
                     'py':counter_python
                     }

OUTPUT_TYPE = {
               'c':report_console,
               'xml':report_xml,
               'csv':report_csv
               }

IGNORE_TYPE = {
               'cs':'g.cs'
               }

def get_file_list(pathname, file_extension_name, filenames):
    
        if os.path.isfile(pathname):
            if pathname.endswith(file_extension_name):
                if not pathname.endswith('g.cs'):
                    filenames.append(pathname)
            return
        
        for name in os.listdir(pathname):
            dir = os.path.join(pathname, name)

            if name.startswith('.'):
                continue
            get_file_list(dir, file_extension_name, filenames)
    
        return
        
        
def main():
    initial_command_option()
    (options, args) = parser.parse_args()
    
    if options.gui:
        from tksclct import run
        run()
        
        return
    
    pathname = options.path
    if pathname is None:
        if len(args) == 0:
            print 'please input last one argument'
            return
        else:
            pathname = args[0]
    
    if not os.path.exists(pathname):
        print "%s is not exist" % pathname

    file_types = options.count_file_type.split('|')
    begin = time.clock()
    print datetime.datetime.today()
    print 'filename\ttotal\tsource\tcomments\tspace'
    
    for file_type in file_types:
        if not SUPPORT_FILE_TYPE.has_key(file_type):
            print "pySCC don't support %s file" % file_type
            continue
        
        counter = SUPPORT_FILE_TYPE[file_type]
        
        filenames = []
        get_file_list(pathname, file_type, filenames)
        
        dict_type_result = []
        all_comments = 0
        all_source = 0
        all_space = 0
        all_total = 0
        all_file_count = 0
        
        for filename in filenames:
            result = counter(filename)
            dict_type_result.append(result)
            
            all_total += result[1]
            all_source += result[2]
            all_comments += result[3]
            all_space += result[4]
            
            all_file_count += 1
        #endfor
        
        print 'summary: file count: %d lines: %d source line: %d comments line: %d space line: %d' % \
            (all_file_count, all_total, all_source, all_comments, all_space)
        report_csv('', dict_type_result)
    #endfot
    end = time.clock()
    print '%f' % (end - begin)
    print datetime.datetime.today()
    
if __name__ == '__main__':
    main()
    
